﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;

namespace Smith.ImageConverter
{
    public partial class ConvertForm : Form
    {
        private string[] filelist = null;
        private BackgroundWorker process = null;
        private ConverterTask task = null;

        public ConvertForm(ListView.ListViewItemCollection taskList)
        {
            InitializeComponent();

            filelist = new string[taskList.Count];
            for (int i = 0; i < taskList.Count; i++)
                filelist[i] = taskList[i].SubItems[0].Text;
            ProcessProgress.Maximum = filelist.Length;

            task = new ConverterTask(filelist);

            // init process worker #1
            process = new BackgroundWorker();
            process.WorkerReportsProgress = true;
            process.DoWork += new DoWorkEventHandler(DoConvertWork);
            process.ProgressChanged += new ProgressChangedEventHandler(process_ProgressChanged);
            process.RunWorkerCompleted += new RunWorkerCompletedEventHandler(process_RunWorkerCompleted);
        }        

        private void FormLoad(object sender, EventArgs e)
        {            
            process.RunWorkerAsync(task);
        }

        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            process.Dispose();
        }

        private void DoConvertWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            ConverterTask task = e.Argument as ConverterTask;

            task.InitializeTask();
            int total = task.TotalCount;

            for (int i = total - 1; i >= 0; i--)
            {
                if (isCancel) break;

                TaskItem item = task.TaskList[i];
                task.Process(item);
                worker.ReportProgress(Convert.ToInt32((total - i) * 100 / task.TotalCount));
            }
        }

        void process_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            StateText.Text = "Converting " + e.ProgressPercentage + "%";
            ProcessProgress.PerformStep();
        }

        void process_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BtnAction.Text = "Complete";
        }

        private void OnActionButtonClick(object sender, EventArgs e)
        {
            if (BtnAction.Text == "Cancel")
            {
                isCancel = true;
            }
        }

        bool isCancel = false;
    }

}
